package hn.cch.https;

import hn.cch.netty.NettyConstant;
import hn.cch.netty.NettyContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP事件通道
 */
public class HttpsChannel extends ChannelInitializer<SocketChannel> {

    private static Logger logger = LoggerFactory.getLogger(HttpsChannel.class);

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {



        // netty通过SslContext创建SslHandler实现https
        NettyContext nettyContext = new NettyContext(
                NettyConstant.crtPath, NettyConstant.keyPath, NettyConstant.pemPath);
        SslContext sslContext = nettyContext.getSslContext();
        if (sslContext != null){
            logger.info("https channel ssl context ");
            SslHandler sslHandler = sslContext.newHandler(ch.alloc());
            ch.pipeline().addLast(sslHandler);
        }


        // HttpServer接收httpRequest要使用HttpRequestDecoder进行解码
        ch.pipeline().addLast(new HttpRequestDecoder());
        // HttpServer发送httpResponse要使用HttpResponseEncoder进行编码
        ch.pipeline().addLast(new HttpResponseEncoder());
        // HttpServer接收httpRequest请求使用HTTP事件处理发送httpResponse响应
        ch.pipeline().addLast(new HttpsHandler());
    }
}
